import oss2
from itertools import islice
class aliyun_oss(object):
    def __init__(self,endpoint,AccessKeyId,AccessKeySecret,bucket_name):
        """endpoint 地区
           auth 认证信息 oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
           bucket 名字
        """
        self.endpoint = endpoint 
        self.AccessKeyId = AccessKeyId
        self.AccessKeySecret = AccessKeySecret
        self.bucket_name = bucket_name

    def oss_list(self):
        """获取oss文件列表
        """
        auth=oss2.Auth(self.AccessKeyId,self.AccessKeySecret)
        bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
        for b in islice(oss2.ObjectIterator(bucket), 1000):
            print(b.key)

    def file_get(self,file_name):
        """获取文件信息
           file_name 文件名 （"IOS/MGOverseasCompass_6ios.ipa"）
        """
        auth=oss2.Auth(self.AccessKeyId,self.AccessKeySecret)
        bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
        simplifiedmeta = bucket.get_object_meta(file_name)
        Last_Modified = simplifiedmeta.headers['Last-Modified']
        # print(simplifiedmeta.headers['Last-Modified']) 
        # print(simplifiedmeta.headers['Content-Length']) 
        # print(simplifiedmeta.headers['ETag']) 
        return Last_Modified

    def oss_download(self,server_file,local_file):
        """下载oss文件
           server_file 远程文件路径
           local_file 下载到本地文件名
        """
        auth=oss2.Auth(self.AccessKeyId,self.AccessKeySecret)
        bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
        bucket.get_object_to_file(server_file,local_file)

    def oss_put(self,server_file,local_file):
        """上传oss文件
           server_file 远程文件路径
           local_file 下载到本地文件名
        """
        auth=oss2.Auth(self.AccessKeyId,self.AccessKeySecret)
        bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
        bucket.put_object_from_file(server_file,local_file)   

    def oss_del(self,delete_file):
        """上传oss文件
           delete_file 要删除远程文件得路径
        """
        auth=oss2.Auth(self.AccessKeyId,self.AccessKeySecret)
        bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
        bucket.delete_object(delete_file)  

